import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Anastasia
 * Date: 16.12.14
 * Time: 12:38
 * To change this template use File | Settings | File Templates.
 */
public class AddDepartment  extends JFrame implements ActionListener {


    private Department department;

    private  AddDepartment adddep;

   private ArrayList<Employee> employees;
     private int index ;


    private JLabel label;
    private JPanel panel;
    private JTextField name ;

    private JButton withoutChief;
    private JButton chieffromList;
    private JButton changer;
    private JLabel chief;

    private JComboBox list;

    private JButton ok;
    //private JButton newEmployee;

    public AddDepartment()
    {
        department = new Department();
        index=-1;
    }

    public class Changer extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {
                panel.remove(changer);
                panel.remove(chief);
                panel.add(chieffromList);
                panel.add(withoutChief);

                panel.repaint();
                panel.validate();

            }
            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }


    public class Selector extends Thread implements ActionListener     //обработчик на выбор сотрудника;
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {

                index = list.getSelectedIndex();
              //  System.out.print(index);

             Employee employee = employees.get(index);
              chief = new JLabel(employee.getName()+" "+employee.getLastName());
                department.setEmployee(employee);
                changer = new JButton("Изменить");
                changer.setBounds(300, 100, 200, 30);

                changer.addActionListener(new Changer());
                panel.add(changer);
                panel.remove(list);
                chief.setBounds(50, 100, 200, 30);
                panel.add(chief);
                panel.repaint();
                panel.validate();

            }
            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }




    public class Sender extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {

                department.setName(name.getText());

                InetAddress addr = InetAddress.getByName(null);



                Socket socket = new Socket(addr, 8080);

                // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                out.writeObject(new Exchanger(2,department));
                //  System.out.println("Ok");

                out.flush();  //чудный метод.


                ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                Object object = in.readObject();


                String data = (String)object;

                if (data.equals("0"))
                {


                    adddep.dispose();
                    JOptionPane.showMessageDialog(null,"Отдел добавлен", "OK",
                            JOptionPane.INFORMATION_MESSAGE);

                }
                else{
                    if(data.equals("1"))
                    {    JOptionPane.showMessageDialog(null,"Неверное название отдела", "Error",
                            JOptionPane.ERROR_MESSAGE);

                    }


                }


               /*
                if(index!=-1)
                {
                    Object mas[] = new Object[2];
                    mas[0] = index;
                    mas[1] = department;

                    out.writeObject(new Exchanger(21,mas));
                    out.flush();


                }  */

                out.close();
                in.close();
                socket.close();

                if(index!=-1)
                {
                    Object mas[] = new Object[2];
                    mas[0] = index;
                    mas[1] = department;

                    InetAddress addr1 = InetAddress.getByName(null);



                    Socket socket1 = new Socket(addr1, 8080);

                    // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    ObjectOutputStream out1 = new ObjectOutputStream(new BufferedOutputStream(socket1.getOutputStream()));
                    out1.writeObject(new Exchanger(21,mas));
                    //  System.out.println("Ok");

                    out1.flush();  //чудный метод.



                }





            }
            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }


    public class WithoutChief extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {
                index =-1;
                //System.out.print(index);

                department.setEmployee(null);
                panel.remove(chieffromList);
                panel.remove(withoutChief);
                panel.repaint();

                changer = new JButton("Изменить");
                changer.setBounds(300, 100, 200, 30);

                changer.addActionListener(new Changer());
                panel.add(changer);
                if(department.getEmployee()==null)
                {
                    chief = new JLabel("Отдел пока что без начальника");
                }
                else {
                    chief = new JLabel(department.getEmployee().getLastName());}

                chief.setBounds(50, 100, 200, 30);
                panel.add(chief);
                panel.repaint();
                panel.validate();


            }

            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }



    public class GetterofEmployees extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {
                // JOptionPane.showMessageDialog(null,"Список отделов пуст", "Inane error",
                // JOptionPane.ERROR_MESSAGE);




                InetAddress addr = InetAddress.getByName(null);
                Socket socket = new Socket(addr, 8080);

                ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                out.writeObject(new Exchanger(31,null));
                //  System.out.println("Ok");

                out.flush();  //чудный метод.

                ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                Object object = in.readObject();

                employees = (ArrayList<Employee>)object;



                if(employees == null||employees.size()==0)
                {
                    JOptionPane.showMessageDialog(null,"Список сотрудников пуст", "Error",
                            JOptionPane.ERROR_MESSAGE);


                }
                else{


                    panel.remove(chieffromList);
                    panel.remove(withoutChief);
                    panel.repaint();


                    String info[]= new String[employees.size()];

                    for(int i =0;i< employees.size();i++)
                    {
                        info[i]=employees.get(i).getInfo();
                    }
                    list = new JComboBox(info);

                    list.addActionListener(new Selector());
                    list.setBounds(50,150,100,50);
                    list.setVisible(true);
                    panel.add(list);
                    panel.repaint();
                    panel.validate();

                }

            }

            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }


    public void actionPerformed(ActionEvent arg0)
    {

          /* try{
          InetAddress addr = InetAddress.getByName(null);

            Socket socket = new Socket(addr, 8080);

            //         BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter outer = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())), true);
            outer.println(3);  //это будет команда


            socket.close();  }

        catch(UnknownHostException e)
        {

        }

        catch(IOException e)
        {

        }         */




        adddep = new AddDepartment();
        adddep.setVisible(true);
        adddep.setBounds(100, 200, 500, 500);
        panel = new JPanel();
        panel.setLayout(null);




        label = new JLabel("Название отдела");
       label.setBounds(50,20,150,30);
        panel.add(label) ;

        name = new JTextField();
        name.setBounds(220, 20, 200, 30);

        panel.add(name);



        withoutChief = new JButton("Без начальника");
       withoutChief.setBounds(5,100,200,30);
        panel.add(withoutChief);

        withoutChief.addActionListener(new WithoutChief());
        chieffromList = new JButton("Из списка");
       chieffromList.setBounds(215,100,200,30);
        panel.add(chieffromList);

        chieffromList.addActionListener(new GetterofEmployees());


        ok = new JButton("OK");
        ok.setBounds(200,150,200,30);
        panel.add(ok);
        ok.addActionListener(new Sender());


     //  newEmployee = new JButton("Новый начальник");
    //    newEmployee.setBounds(430,100,200,30);
      //  panel.add(newEmployee);

      // newEmployee.addActionListener(new AddChief());

        panel.validate();



        adddep.add(panel);
        adddep.setPreferredSize(new Dimension(500, 800));



    }
}

